<!--
* description: 门店移库审核
* author: duanhy
* createdDate: 2020-11-16
-->
<template>
  <div class="app-container app-container-table">
    <!-- 单表格模版页面 -->
    <one-table-template
      ref="multipleTable"
      :dynamic-api-config="apiConfig"
      :dynamic-buttons="dynamicButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="dynamicTableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="false"
      :dynamic-is-show-select="true"
      :dynamic-export-converts="dynamicExportConverts"
      :refresh-table-key="refreshTableKey"
      :callback-obj="callbackObj"
    />
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import transferApi from '@/api/apiVeTransferManagement'
import api from '@/api/apiVeData'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'

export default {
  name: 'VeStoreMove',
  components: {
    OneTableTemplate
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      }
    )
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      dlrId: '',
      selectList: [],
      refreshTableKey: '0',
      // table表格查询API配置对象
      apiConfig: transferApi.queryMoveVerify,
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
            .tableComponents
          : [
            // 显示组件
            {
              compKey: 'compKey1',
              labelName: '移库单：',
              codeField: 'movestockOrderCode',
              isMul: false,
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: 'VIN码：',
              codeField: 'vin',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '源仓库：',
              codeField: 'oldHouseId',
              textField: 'oldHouseName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'oldHouseId,oldHouseName',
              type: 'dropdownList',
              isMust: true,
              options: [
                { oldHouseId: '', oldHouseName: '' }
              ]
            },
            {
              compKey: 'compKey4',
              labelName: '目的库：',
              codeField: 'stockId',
              textField: 'stockName',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true,
              oFields: 'stockId,stockName',
              customObj: {
                api: transferApi.ListOfWarehouse,
                listQuery: {
                  warehouseId: '1'
                }
              }
            },
            {
              compKey: 'compKey5',
              labelName: '单据状态：',
              codeField: 'auditStatusName',
              component: () => import('@/components/org/LookupValue'),
              lookuptype: 'VE1079',
              type: 'dropdownList',
              isMust: false
            },
            {
              compKey: 'compKey7',
              labelName: '申请时间：',
              codeField: 'applyTimeStart,applyTimeEnd',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey8',
              labelName: '审核时间：',
              codeField: 'auditTimeStart,auditTimeEnd',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey9',
              labelName: '车系：',
              codeField: 'carSeriesId',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              oFields: 'carSeriesId,carSeriesCn',
              customObj: {
                api: api.listOfCarSeries
              }
            },
            {
              compKey: 'compKey10',
              labelName: '基础车型：',
              codeField: 'carConfigId',
              textField: 'carConfigCn',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              oFields: 'carConfigId,carConfigCn',
              parentFileds: 'value:carSeriesId',
              customObj: {
                api: api.queryCarType,
                listQuery: {
                  carSeriesId: ''
                }
              }
            },
            {
              compKey: 'compKey11',
              labelName: '选装包：',
              codeField: 'optionalPagId',
              textField: 'optionalPagName',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              oFields: 'optionalPagId,optionalPagName',
              parentFileds: 'value:carConfigId',
              customObj: {
                api: api.queryCarOptionalPagLinkMessage,
                listQuery: {
                  carConfigId: ''
                }
              }
            },
            {
              compKey: 'compKey12',
              labelName: '车身颜色：',
              codeField: 'carColorId',
              textField: 'carColorName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'carColorId,carColorName',
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              parentFileds: 'value:carConfigId|carSeriesId|optionalPagId',
              customObj: {
                listQuery: {
                  carConfigId: '', carSeriesId: '', optionalPagId: ''
                },
                api: api.queryCarColorLinkMessage
              }
            },
            {
              compKey: 'compKey13',
              labelName: '内饰颜色：',
              codeField: 'carIncolorId',
              textField: 'carIncolorName',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'carIncolorId,carIncolorName',
              type: 'dropdownList',
              isMul: false,
              isMust: false,
              parentFileds: 'value:carConfigId|carSeriesId|optionalPagId',
              customObj: {
                listQuery: {
                  carConfigId: '', carSeriesId: '', optionalPagId: ''
                },
                api: api.queryCarInColorLinkMessage
              }
            }
          ],
      // form 的表单对象
      formField: {
        oldHouseId: '',
        stockId: '',
        carSeriesId: '',
        carConfigId: '',
        optionalPagId: '',
        carColorId: '',
        carIncolorId: '',
        auditStatusName: '',
        auditTimeStart: '',
        auditTimeEnd: '',
        applyTimeStart: '',
        applyTimeEnd: '',
        vin: '',
        movestockOrderCode: '',
        auditOpinion: ''
      },
      // 动态组件-按钮
      dynamicButtons:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
          : [
            {
              compKey: 'btnKey1',
              type: '',
              size: 'small',
              clickEvent: () => this.adopt(),
              text: '审核通过',
              name: '',
              position: 'left',
              fuzzySearch: true,
              disabled: true
            },
            {
              compKey: 'btnKey2',
              type: '',
              size: 'small',
              clickEvent: () => this.reject(),
              text: '驳回',
              name: '',
              position: 'left',
              fuzzySearch: true,
              disabled: true
            },
            {
              compKey: 'btnKey3',
              type: 'primary',
              size: 'small',
              clickEvent: () => this.queryTable(1),
              text: '查询',
              name: 'search',
              position: 'right',
              fuzzySearch: true
            },
            {
              compKey: 'btnKey4',
              type: '',
              size: 'small',
              clickEvent: () => this.reset(),
              text: '重置',
              name: 'reset',
              position: 'right'
            }
          ],
      // 动态组件-表格网格列
      dynamicTableCols:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length >
          0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
          : [
            {
              prop: 'movestockOrderCode',
              label: '移库单号',
              width: 120
            },
            {
              prop: 'oldHouseName',
              label: '源仓库',
              width: 140
            },
            {
              prop: 'stockName',
              label: '目的库'
            },
            {
              prop: 'auditStatusName',
              label: '单据状态'
            },
            {
              prop: 'auditOpinion',
              label: '审核意见',
              isComponent: true,
              width: 180,
              align: 'center',
              comps: [
                {
                  compKey: 'propKey0',
                  codeField: 'auditOpinion',
                  component: () => import('@/components/org/commonInput'),
                  type: 'inputText',
                  align: 'center',
                  rowFileds: 'disabled:auditStatusName-审核驳回-true|disabled:auditStatusName-审核通过-true'
                }
              ]
            },
            {
              prop: 'vin',
              label: 'VIN',
              width: 140
            },
            {
              prop: 'carSeriesCn',
              label: '车系'
            },
            {
              prop: 'carConfigCn',
              label: '基础车型'
            },
            {
              prop: 'optionalPagName',
              label: '选装包'
            },
            {
              prop: 'carColorName',
              label: '车身颜色'
            },
            {
              prop: 'carIncolorName',
              label: '内饰颜色'
            },
            {
              prop: 'newDate',
              label: '制单日期'
            },
            {
              prop: 'applyMen',
              label: '申请人'
            },
            {
              prop: 'applyTime',
              label: '申请时间'
            },
            {
              prop: 'auditMen',
              label: '审核人'
            },
            {
              prop: 'auditTime',
              label: '审核时间'
            }
          ],
      // 字段格式化转换（用于导出excel）（kvs表示键值转换）
      dynamicExportConverts: {
        isEnable: {
          convert: 'kvs',
          kvs: {
            '1': '是',
            '0': '否'
          }
        }
      },
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件
        onCheckSelectChange: (selection) => {
          if (selection.length === 0) {
            this.dynamicButtons[0].disabled = true
            this.dynamicButtons[1].disabled = true
          }
          if (selection !== 0) {
            this.dynamicButtons[0].disabled = false
            this.dynamicButtons[1].disabled = false
            this.selectList = selection
          }
        }
      }
    }
  },
  mounted() {
    // 列表查询
    const that = this
    this.queryTable(1)
    setTimeout(() => {
      that.dlrId = that.$refs['multipleTable'].list[0].dlrId
      console.log(that.dlrId)
      that.init()
    }, 3000)
  },
  methods: {
    // 获取单据状态
    // 设置表格选择框 是否禁用
    getSelectable(row, index) {
      if (row.auditStatusName === '已申请') {
        return true
      }
    },
    // 判断数组是否含有重复元素
    isRepeat(arr) {
      var hash = {}
      for (var i in arr) {
        if (hash[arr[i]]) {
          return true
        }
        // 不存在该元素，则赋值为true，可以赋任意值，相应的修改if判断条件即可
        hash[arr[i]] = true
      }
      return false
    },
    // 审核通过
    adopt() {
      if (this.selectList.length > 0) {
        var vinlist = []
        for (let index = 0; index < this.selectList.length; index++) {
          vinlist.push(this.selectList[index].vin)
        }
        if (this.isRepeat(vinlist)) {
          this.$message({ message: '同一辆车不可提交多条移库申请', type: 'warn', uration: 2000 })
          return false
        }
        this.$requestAPI(this.$getParams({
          apiConfig: transferApi.moveVerifyAdopt,
          variables: this.selectList
        })).then(response => {
          if (response.result === '0') {
            if (response.msg) {
              this.$message({ message: response.msg, type: 'warn', uration: 2000 })
            }
            return
          }
          this.$message({ message: response.msg, type: 'warn', uration: 2000 })
          this.selectList = []
          setTimeout(() => {
            this.queryTable(1)
          }, 2000)
        }).catch(err => {
          console.info(err)
        })
      }
    },
    // 驳回
    reject() {
      if (this.selectList.length === 0 || this.selectList === []) {
        return this.$message({ message: '请选择驳回', type: 'warn', uration: 2000 })
      }
      const obj = {
        updateControlIds: [],
        movestockOrderIds: [],
        vins: [],
        auditOpinions: []
      }
      for (const k in this.selectList) {
        obj.updateControlIds.push(this.selectList[k].updateControlId)
        obj.movestockOrderIds.push(this.selectList[k].movestockOrderId)
        obj.vins.push(this.selectList[k].vin)
        obj.auditOpinions.push(this.selectList[k].auditOpinion)
      }
      this.$requestAPI(this.$getParams({
        apiConfig: transferApi.moveVerifyReject,
        variables: obj
      })).then(response => {
        if (response.result === '0') {
          if (response.msg) {
            this.$message({ message: response.msg, type: 'warn', uration: 2000 })
          }
          return
        }
        this.$message({ message: response.msg, type: 'warn', uration: 2000 })
        setTimeout(() => {
          this.queryTable(1)
        }, 2000)
      }).catch(err => {
        console.info(err)
      })
    },

    // 获取门店id
    init() {
      const newSelect = []
      this.$requestAPI(this.$getParams({
        apiConfig: transferApi.ListOfWarehouse,
        variables: {
          isEnable: '1',
          pageIndex: 1,
          pageSize: 500,
          warehouseId: '1'
        }
      })).then(response => {
        if (response.result === '0') {
          if (response.msg) {
            this.$message({ message: response.msg, type: 'warn', uration: 2000 })
          }
          return
        }
        for (const k in response.rows) {
          newSelect.push({
            oldHouseId: response.rows[k].stockId,
            oldHouseName: response.rows[k].stockName
          })
        }
        for (const k in this.tableComponents) {
          if (this.tableComponents[k].codeField === 'oldHouseId') {
            this.tableComponents[k].options = newSelect
            return false
          }
        }
      }).catch(err => {
        console.info(err)
      })
    }
  }
}
</script>
